import React, { useEffect, useState } from 'react';
import { useLocation, useNavigate } from 'react-router-dom';

import { MetaRouteObject } from '@/routes/type';
import { request } from '@/utils/request';

import { useKeepRoutes } from './components/CacheRouter';

// 不需要验证的路由
export const notNeedAuth: string[] = ['/auth', '/home', '/instructions'];

const AuthRoute: React.FC<{
  routes: MetaRouteObject[];
}> = props => {
  const { routes } = props;
  const [isAuthorized, setIsAuthorized] = useState<boolean>(false);
  const location = useLocation();
  const navigate = useNavigate();

  // 递归查询某个路由具体信息
  const queryPathInfo = (routes: MetaRouteObject[], pathname: string): MetaRouteObject | null => {
    for (let r of routes) {
      if (pathname === r.path) {
        return r;
      }
      if (r?.children) {
        queryPathInfo(r.children, pathname);
      }
    }
    return null;
  };

  // 路由守卫
  useEffect(() => {
    if (!isAuthorized && !notNeedAuth.includes(location.pathname)) {
      (async () => {
        await request('POST', '/auth')
          .then(async () => {
            await setIsAuthorized(true);
          })
          .catch(async () => {
            await navigate('/auth');
          });
      })();
    }
  }, [routes, location, navigate]);

  return useKeepRoutes();
};

export default AuthRoute;
